package springboot.tools.state.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import springboot.tools.state.common.TaskRouter;
import springboot.tools.state.model.CitReportOpsInfoPO;
import springboot.tools.state.model.CitTaskConst;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 任务分发管理
 */
@Component
public class CitTaskDispatcher implements BeanPostProcessor {

    private Logger LOGGER = LoggerFactory.getLogger(getClass());


    /**
     * 路由数据集合
     */
    private static Map<String, CitTaskHandler> bizRouterMap = new HashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * 将实现CitTaskHandler接口的类 放入到map中 方便下一步的查找和调用
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof CitTaskHandler) {
            Class<?> targetClass;
            if (AopUtils.isAopProxy(bean)) {
                targetClass = AopUtils.getTargetClass(bean);
            } else {
                targetClass = bean.getClass();
            }
            TaskRouter annotation = targetClass.getAnnotation(TaskRouter.class);
            if (annotation != null) {
                String[] taskList = annotation.value();
                if (taskList != null) {
                    for (String task : taskList) {
                        bizRouterMap.put("citTask#" + task, (CitTaskHandler) bean);
                    }
                }
            }
        }
        return bean;
    }


    /**
     * 根据任务ID查询任务进行分发
     */
    public void dispatcher(Long taskId) {
        CitReportOpsInfoPO opsInfoPO = null;
        //查询任务
        //citReportOpsInfoPOMapper.selectByPrimaryKey(taskId);
        if (CitTaskConst.Status.TASK_STATUS_FINISH.equals(opsInfoPO.getOpsStatus())) {
            LOGGER.info("任务已结束");
            return;
        }
        if (opsInfoPO == null) {
            LOGGER.error("任务为空......");
            return;
        }
        //根据参数 获取存储在map中需要处理的实现类
        CitTaskHandler citTaskHandler = bizRouterMap.get("citTask#" + opsInfoPO.getOpsType() + "-" + opsInfoPO.getOpsStatus());
        if (citTaskHandler == null) {
            LOGGER.error("未获取到TaskHandler,taskId={}", opsInfoPO.getId());
            return;
        }
        citTaskHandler.handle(opsInfoPO.getId());
    }
}
